package com.crm.service.impl;


import cn.hutool.core.bean.BeanUtil;

import cn.hutool.json.JSONUtil;
import com.crm.domain.dto.LoginDto;
import com.crm.domain.entity.CaptchaResponse;
import com.crm.domain.entity.User;
import com.crm.domain.vo.UserVo;
import com.crm.exception.BaseException;
import com.crm.mapper.UserManagementMapper;
import com.crm.properties.JwtTokenManagerProperties;
import com.crm.service.LoginService;
import com.crm.utils.*;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.crm.base.ResponseResult.success;


@Service
@RequiredArgsConstructor
public class LoginServiceImpl implements LoginService {

    private final UserManagementMapper userManagementMapper;
    private final JwtTokenManagerProperties jwtTokenManagerProperties;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 创建验证码，存入redis
     *
     * @param request
     * @return
     */

    @Override
    public CaptchaResponse createCode(HttpServletRequest request) throws IOException {
        CaptchaResponse captchaResponse = new CaptchaResponse();
        captchaResponse.setCode(success().getCode());
        captchaResponse.setMsg(success().getMsg());

        // 生成验证码图片
        String captchaImage = CaptchaUtil.generateCaptcha(request);
        captchaResponse.setImg(captchaImage);


        String correctCode =  request.getSession().getAttribute("captchaResult").toString();

        stringRedisTemplate.opsForValue().set("correctCode", correctCode,100,TimeUnit.SECONDS);
        return captchaResponse;
    }

    /**
     * 用户登录
     *
     * @param loginDto
     * @return
     */
    @Override
    public UserVo login(LoginDto loginDto) {
        User user = userManagementMapper.getUser(loginDto.getUsername());

        if (ObjectUtil.isEmpty(user)) {
            throw new BaseException(BasicEnum.USER_EMPTY_EXCEPTION);
        }
        //密码校验
        if (!user.getPassword().equals(loginDto.getPassword())) {
            throw new BaseException(BasicEnum.PASSWORD_ERROR);
        }
        //验证码校验
        String correctCode = stringRedisTemplate.opsForValue().get("correctCode");
        if (null == correctCode){
            throw new BaseException(BasicEnum.VERIFICATION_CODE_ERROR);
        }
        if(!correctCode.equals(loginDto.getCode())){
            throw new BaseException(BasicEnum.VERIFICATION_CODE_ERROR);
        }
        //账号状态校验
        if (0 != user.getStatus()) {
            throw new BaseException(BasicEnum.USER_STATUS_EXCEPTION);
        }
        UserVo userVo = null;

        try {
            //对象的转换
            userVo = BeanUtil.toBean(user, UserVo.class);
        } catch (Exception e) {
            String message = e.getMessage();
            System.out.println(message);
        }

        //密码脱敏
        userVo.setPassword("");


        //生成jwt的token
        Map<String, Object> claims = new HashMap<>();
        claims.put("currentUser", JSONUtil.toJsonStr(userVo));
        String token = JwtUtil.createJWT(jwtTokenManagerProperties.getBase64EncodedSecretKey(), jwtTokenManagerProperties.getTtl(), claims);
        userVo.setUserToken(token);

        return userVo;
    }

}
